<template>
  <div style="width: 100%;">
    <h2>小区收费明细</h2>
    <div class="search-bar">
      <el-input v-model="ownerId" placeholder="请输入业主ID" style="width: 130px;"></el-input>
      <el-input v-model="houseId" placeholder="请输入房屋ID" style="width: 130px;"></el-input>
      <el-input v-model="chargeId" placeholder="请输入收费项目ID" style="width: 140px;"></el-input>
      <el-input v-model="propertyStaffId" placeholder="请输入物业人员ID" style="width: 140px;"></el-input>
      <el-input v-model="feeMonth" placeholder="请输入费用月" style="width: 130px;"></el-input>
      <el-select v-model="paymentStatus" placeholder="请选择缴费状态" style="width: 140px;">
        <el-option label="未缴费" value="0"></el-option>
        <el-option label="已缴费" value="1"></el-option>
      </el-select>
      <el-button @click="fetchChargeDetails" style="width: 70px;">查询</el-button>
      <el-button type="primary" @click="openGenerateOrderDialog" style="width: 140px;">生成当月缴费订单</el-button>
      <el-button type="primary" @click="openAddChargeItemDialog" style="width: 120px;">新增收费项目</el-button>
      <el-button type="primary" @click="openUpdateChargeItemDialog" style="width: 120px;">修改收费项目</el-button>
      <el-button type="primary" @click="openDeleteChargeItemDialog" style="width: 120px;">删除收费项目</el-button>
    </div>
    <div v-if="isLoading">加载中···</div>
    <el-table v-else :data="chargeDetailList" stripe style="width: 100%">
      <el-table-column prop="id" label="收费明细ID"></el-table-column>
      <el-table-column prop="ownerId" label="业主ID"></el-table-column>
      <el-table-column prop="houseId" label="房屋ID"></el-table-column>
      <el-table-column prop="chargeId" label="收费项目ID"></el-table-column>
      <el-table-column prop="propertyStaffId" label="物业人员ID"></el-table-column>
      <el-table-column prop="feeMonth" label="费用月"></el-table-column>
      <el-table-column prop="paymentStatus" label="缴费状态">
        <template #default="scope">
          {{ scope.row.paymentStatus === 0? '未缴费' : '已缴费' }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 生成订单对话框 -->
    <el-dialog v-model="generateOrderDialogVisible" title="生成小区当月缴费订单">
      <el-form :model="generateOrderForm" label-width="120px">
        <el-form-item label="月份">
          <el-input v-model="generateOrderForm.month" placeholder="请输入月份（1-12）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateOrderDialogVisible = false">取消</el-button>
        <el-button @click="generateChargeDetails">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增收费项目对话框 -->
    <el-dialog v-model="addChargeItemDialogVisible" title="新增收费项目">
      <el-form :model="addChargeItemForm" label-width="120px">
        <el-form-item label="收费项目名称">
          <el-input v-model="addChargeItemForm.chargeName" placeholder="请输入收费项目名称"></el-input>
        </el-form-item>
        <el-form-item label="单位金额">
          <el-input v-model="addChargeItemForm.amount" placeholder="请输入单位金额"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addChargeItemForm.remark" placeholder="请输入备注（可选）"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <input type="file" ref="attachmentInput" style="display: none;" @change="handleAttachmentChange">
          <el-button @click="openAttachmentSelector">选择附件（可选）</el-button>
          <span v-if="addChargeItemForm.attachmentName">{{ addChargeItemForm.attachmentName }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addChargeItemDialogVisible = false">取消</el-button>
        <el-button @click="addChargeItem">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改收费项目对话框 -->
    <el-dialog v-model="updateChargeItemDialogVisible" title="修改收费项目">
      <el-form :model="updateChargeItemForm" label-width="120px">
        <el-form-item label="收费项目ID">
          <el-input v-model="updateChargeItemForm.id" placeholder="请输入收费项目ID"></el-input>
        </el-form-item>
        <el-form-item label="收费项目名称">
          <el-input v-model="updateChargeItemForm.chargeName" placeholder="请输入收费项目名称（可选）"></el-input>
        </el-form-item>
        <el-form-item label="单位金额">
          <el-input v-model="updateChargeItemForm.amount" placeholder="请输入单位金额（可选）"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="updateChargeItemForm.remark" placeholder="请输入备注（可选）"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <input type="file" ref="updateAttachmentInput" style="display: none;" @change="handleUpdateAttachmentChange">
          <el-button @click="openUpdateAttachmentSelector">选择附件（可选）</el-button>
          <span v-if="updateChargeItemForm.attachmentName">{{ updateChargeItemForm.attachmentName }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateChargeItemDialogVisible = false">取消</el-button>
        <el-button @click="updateChargeItem">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除收费项目对话框 -->
    <el-dialog v-model="deleteChargeItemDialogVisible" title="删除收费项目">
      <el-form :model="deleteChargeItemForm" label-width="120px">
        <el-form-item label="收费项目ID">
          <el-input v-model="deleteChargeItemForm.id" placeholder="请输入收费项目ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deleteChargeItemDialogVisible = false">取消</el-button>
        <el-button @click="deleteChargeItem">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const token = localStorage.getItem("token");
const headers = {
  Authorization: token
};

const isLoading = ref(false);
const chargeDetailList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const ownerId = ref(null);
const houseId = ref(null);
const chargeId = ref(null);
const propertyStaffId = ref(null);
const feeMonth = ref(null);
const paymentStatus = ref(0);
const generateOrderDialogVisible = ref(false);
const generateOrderForm = ref({
  month: null
});

const addChargeItemDialogVisible = ref(false);
const addChargeItemForm = ref({
  chargeName: null,
  amount: null,
  remark: null,
  attachment: null,
  attachmentName: null
});

const updateChargeItemDialogVisible = ref(false);
const updateChargeItemForm = ref({
  id: null,
  chargeName: null,
  amount: null,
  remark: null,
  attachment: null,
  attachmentName: null
});

const deleteChargeItemDialogVisible = ref(false);
const deleteChargeItemForm = ref({
  id: null
});

const dataLoaded = ref(false);

const getChargeDetailList = async () => {
  if (
      !ownerId.value &&
      !houseId.value &&
      !chargeId.value &&
      !propertyStaffId.value &&
      !feeMonth.value &&
      paymentStatus.value === null
  ) {
    ElMessage.warning('请选查询内容');
    return;
  }

  isLoading.value = true;
  try {
    const response = await axios.get('/api/charge-details/property/page', {
      headers,
      params: {
        current: currentPage.value,
        size: pageSize.value,
        ownerId: ownerId.value,
        houseId: houseId.value,
        chargeId: chargeId.value,
        propertyStaffId: propertyStaffId.value,
        feeMonth: feeMonth.value,
        paymentStatus: paymentStatus.value
      }
    });
    if (response.data.code === 200) {
      chargeDetailList.value = response.data.data.records;
      total.value = response.data.data.total;
      dataLoaded.value = true;
    } else {
      ElMessage.error('获取收费明细列表失败');
    }
  } catch (err) {
    ElMessage.error(`获取收费明细列表失败：${err.message}`);
  } finally {
    isLoading.value = false;
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getChargeDetailList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getChargeDetailList();
};

const fetchChargeDetails = () => {
  currentPage.value = 1;
  getChargeDetailList();
};

const openGenerateOrderDialog = () => {
  generateOrderDialogVisible.value = true;
};

const generateChargeDetails = async () => {
  const month = generateOrderForm.value.month;
  if (!month || month < 1 || month > 12) {
    ElMessage.warning('请输入1-12之间的有效月份');
    return;
  }
  try {
    const response = await axios.post('/api/charge-details/property/add', null, {
      headers,
      params: {
        month: month
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('生成小区当月缴费订单成功');
      generateOrderDialogVisible.value = false;
      getChargeDetailList();
    } else {
      ElMessage.error('生成小区当月缴费订单失败');
    }
  } catch (err) {
    ElMessage.error(`生成小区当月缴费订单失败：${err.message}`);
  }
};

const openAddChargeItemDialog = () => {
  addChargeItemDialogVisible.value = true;
};

const addChargeItem = async () => {
  const formData = new FormData();
  formData.append('chargeName', addChargeItemForm.value.chargeName);
  formData.append('amount', addChargeItemForm.value.amount);
  if (addChargeItemForm.value.remark) {
    formData.append('remark', addChargeItemForm.value.remark);
  }
  if (addChargeItemForm.value.attachment) {
    formData.append('attachment', addChargeItemForm.value.attachment);
  }

  try {
    const response = await axios.post('/api/charge-items/property', formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('新增收费项目成功');
      addChargeItemDialogVisible.value = false;
      getChargeDetailList();
      const newChargeItemId = response.data.data.id;
      ElMessage.success(`新增项目成功，项目id为：${newChargeItemId}`);
    } else {
      ElMessage.error('新增收费项目失败');
    }
  } catch (err) {
    ElMessage.error(`新增收费项目失败：${err.message}`);
  }
};

const handleAttachmentChange = (e) => {
  addChargeItemForm.value.attachment = e.target.files[0];
  addChargeItemForm.value.attachmentName = e.target.files[0].name;
};

const openAttachmentSelector = () => {
  const input = document.querySelector('input[type="file"]');
  input.click();
};

const openUpdateChargeItemDialog = () => {
  updateChargeItemDialogVisible.value = true;
};

const updateChargeItem = async () => {
  const formData = new FormData();
  formData.append('id', updateChargeItemForm.value.id);
  if (updateChargeItemForm.value.chargeName) {
    formData.append('chargeName', updateChargeItemForm.value.chargeName);
  }
  if (updateChargeItemForm.value.amount) {
    formData.append('amount', updateChargeItemForm.value.amount);
  }
  if (updateChargeItemForm.value.remark) {
    formData.append('remark', updateChargeItemForm.value.remark);
  }
  if (updateChargeItemForm.value.attachment) {
    formData.append('attachment', updateChargeItemForm.value.attachment);
  }

  try {
    const response = await axios.put('/api/charge-items/property', formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('修改收费项目成功');
      updateChargeItemDialogVisible.value = false;
      getChargeDetailList();
    } else {
      ElMessage.error('修改收费项目失败');
    }
  } catch (err) {
    ElMessage.error(`修改收费项目失败：${err.message}`);
  }
};

const handleUpdateAttachmentChange = (e) => {
  updateChargeItemForm.value.attachment = e.target.files[0];
  updateChargeItemForm.value.attachmentName = e.target.files[0].name;
};

const openUpdateAttachmentSelector = () => {
  const input = document.querySelector('input[type="file"]');
  input.click();
};

const openDeleteChargeItemDialog = () => {
  deleteChargeItemDialogVisible.value = true;
};

const deleteChargeItem = async () => {
  const id = deleteChargeItemForm.value.id;
  try {
    const response = await axios.delete('/api/charge-items/property', {
      headers,
      params: {
        id: id
      }
    });
    if (response.data.code === 200) {
      ElMessage.success('删除收费项目成功');
      deleteChargeItemDialogVisible.value = false;
      getChargeDetailList();
    } else {
      ElMessage.error('删除收费项目失败');
    }
  } catch (err) {
    ElMessage.error(`删除收费项目失败：${err.message}`);
  }
};

onMounted(() => {
  getChargeDetailList();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.el-pagination {
  margin-top: 20px;
}
</style>